<template>
    <PageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="pageData.headerShow">
                <a-form size="mini" :model="pageData" layout="inline">
                    <a-form-item label="仓库类型">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="whChange" placeholder=""
                            v-model="searchData.whTypeName" allow-clear>
                            <a-option v-for="item in whTypeList" :value="item.typeName">
                                {{ item.typeName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="选择公司">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="companyChange" placeholder=""
                            v-model="searchData.firm" allow-clear>
                            <a-option v-for="item in companyList" :value="item.id">
                                {{ item.typeName ? item.typeName + '-' + item.firmName : item.firmName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="仓库">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="searchData.wh"
                            @click="ckisPd" allow-clear @change="isWhilist">
                            <a-option v-for="item in whList" :value="item.warehouseName">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="处理状态">
                        <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" placeholder="" v-model="searchData.stats"
                            allow-clear>
                            <a-option :value="0">待处理</a-option>
                            <a-option :value="1">已处理</a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="pageData.headerShow" @click="pageData.headerShow = false" :strokeWidth="2"
                        :size="18" />
                    <icon-double-down v-else @click="pageData.headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
           
                  <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%;width: 100%;"
                    :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"
                    :localeText="localeText1"></AgGridVuesCopys>
           
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
            style="justify-content: center" :page-size="size" :current="page" />
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" unmount-on-close
            popup-container=".arco-tabs-content" :height="pageData.rHeight" :visible="pageData.showAdd" @ok="sideOk"
            :ok-loading="pageData.pageLoading" placement="bottom" @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-space>
                    <a-space style="margin-bottom:10px;">
                        <a-button type="primary" @click="addLine" size="mini">新增</a-button>
                        <a-button type="primary" @click="delLine" size="mini">删除</a-button>
                    </a-space>
                    <a-form ref="formRef" layout="inline" :model="searchData" size="mini">
                        <a-form-item label-col-flex="80px" label="仓库类型" field="whTypeName" 
                            :rules="[{ required: true, message: '仓库类型必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input :style="{ width: '10rem' }" disabled v-model="searchData.whTypeName"></a-input>
                        </a-form-item>
                        <a-form-item label-col-flex="80px" label="收货公司" field="firm2"
                            :rules="[{ required: true, message: '收货公司必填' }]" :validate-trigger="['change', 'blur']">
                            <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" @change="companyChanges" placeholder=""
                                v-model="searchData.firm2" allow-clear>
                                <a-option v-for="item in companyList" :value="item.id">
                                    {{ item.typeName ? item.typeName + '-' + item.firmName : item.firmName }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label-col-flex="80px" label="收货仓库" field="wh2"
                            :rules="[{ required: true, message: '收货仓库必填' }]" :validate-trigger="['change', 'blur']">
                            <a-select popup-container="html"  class="bacClass" :style="{ width: '10rem' }" v-model="searchData.wh2" allow-clear
                                @change="isWhNames">
                                <a-option v-for="item in whList2" :value="item.id">
                                    {{ item.warehouseName }}
                                </a-option>
                            </a-select>
                        </a-form-item>
                    </a-form>
                </a-space>
                <div style="height:10px ;"></div>
                <div style="min-width:1500px; overflow:auto;" class="scrollbar">
                    <el-scrollbar>
                        <a-table stripe :bordered="true" :columns="tableColumnsWl" size="mini"
                            :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="selectedRowKeysWl"
                            :loading="table.tableLoading" :data="pageData.list" rowKey="id">
                            <template #materialL="{ record }">
                                <div style="width:100%;">
                                    <a-select popup-container="html"  class="bacClass" :loading="loading" :allowClear="true" @search="handleSearch"
                                        v-model="record.materialL" :filter-option="false" allow-search @focus="focusSel">
                                        <a-option v-for="item in pageData.wlListL" :value="item['bigClassName']">{{
                                            item['bigClassName']
                                        }}
                                        </a-option>
                                    </a-select>
                                </div>
                            </template>
                            <template #materialS="{ record }">
                                <div style="width:100%;">
                                    <a-select popup-container="html"  class="bacClass" :loading="loading1" :allowClear="true"
                                        @search="handleSearch1" v-model="record.materialS" :filter-option="false"
                                        allow-search @focus="focusSel1">
                                        <a-option v-for="item in pageData.wlListS" :value="item['subClassName']">{{
                                            item['subClassName']
                                        }}
                                        </a-option>
                                    </a-select>
                                </div>
                            </template>
                            <template #materialName="{ record }">
                                <div style="width:100%;">
                                    <a-select popup-container="html"  class="bacClass" :loading="loading" :allowClear="true" @search="handleSearch2"
                                        v-model="record.materialName" :filter-option="false" allow-search
                                        @focus="focusSel2(record)" @change="changeWl(record, record.materialName)">
                                        <a-option v-for="item in pageData.wlList" :value="item['materialName']">{{
                                            item['materialName']
                                        }}
                                        </a-option>
                                    </a-select>
                                </div>
                            </template>
                            <template #num="{ record }">
                                <div style="width:100%;">
                                    <a-input-number v-model="record.num" class="input-demo bacClass" :min="0"
                                        :max="10000000000" />
                                </div>
                            </template>
                        </a-table>
                    </el-scrollbar>
                </div>
            </div>
        </a-drawer>
</PageTabelLayout>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";
import { localeText } from '@/api/aggridZw'
import { ref, reactive, h, watch } from "vue";
import Toolbar from "@/components/Toolbar.vue";

import PageTabelLayout from "@/components/pageTabelLayout.vue";
import TreeUtils from "@/utils/TreeUtils";
import { FormInstance } from '@arco-design/web-vue/es/form';
import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
import { Message, Modal } from "@arco-design/web-vue";
import { IconDoubleUp, IconDoubleDown, IconEdit, IconFindReplace, IconDelete } from "@arco-design/web-vue/es/icon";
import pagination from "@arco-design/web-vue/es/pagination";
import { table } from "console";
import QrcodeVue from 'qrcode.vue'
import printJS from 'print-js'




export default {
    name: "StockTransferList",

    setup() {

        onMounted(() => {

            //弹出层的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 100;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
                //弹出层的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 100;
                }
            })
        });
        const whService = new WHService()
        const whService1 = new WHService()
        const whList = ref<any[]>([])
        const whList2 = ref<any[]>([])
        const whTypeList = whService.whTypeList

        const whTypeFieldList = whService.whTypeFieldList
        const whTypeFieldList1 = whService1.whTypeFieldList
        const treeUtils = new TreeUtils()
        const companyList: any = whService.companyList
        const selectedRowKeysWl = ref()
        const searchData = reactive<{
            whTypeName: string;
            firm: string,
            firmName2: any,
            firm2: any,
            wh: string,
            wh2: any,
            wh2Name: any,
            stats: any
        }>({
            firm: '',
            firmName2: '',
            firm2: '',
            whTypeName: "",
            wh: '',
            wh2: '',
            wh2Name: '',
            stats: null
        });

        const baseCol: any[] = [{
            dataIndex: 'orderNo',
            key: 'orderNo',
            title: '单号',
            width: 180
        }, {
            dataIndex: 'materialCode',
            key: 'materialCode',
            title: '物料编号',
            width: 150
        }, {
            dataIndex: 'materialName',
            key: 'materialName',
            title: '物料名称',
            width: 150
        },
        {
            dataIndex: 'num',
            key: 'num',
            title: '数量',
            width: 150
        },
        {
            dataIndex: 'unit',
            key: 'unit',
            title: '单位',
            width: 150
        },
        {
            title: '创建人',
            dataIndex: 'createName',
            key: 'createName',
            width: 150
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 150
        },

        {
            title: '处理状态',
            dataIndex: 'auditState',
            slotName: 'auditState',
            width: 100,
            key: 'auditState',
            fixed: "right",
        },
        ]
        let formRef = ref<FormInstance>()
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }

        function doRefresh() {
            pageData.pageLoading = true;
            post({
                url: "wms/WarehousetypeFieldvalue/getInvoicesByPage",
                data: {
                    "page": page.value,
                    "size": size.value,
                    "warehouseTypeName": searchData.whTypeName,
                    "firmId": searchData.firm,
                    "infoType": 3,
                    'infoState': searchData.stats,
                    warehouseName: searchData.wh
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption.value.setRowData(data.list);
                        pagination.setTotalSize(data.total);
                        total.value = data.total
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false;
                });
        }



        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        let tableColumns: any = ref([])
        let tableColumns1: any = ref([])
        const pageData = reactive<{
            showAdd: boolean
            sideTitle: string
            pageLoading: boolean
            headerShow: boolean
            rHeight: any
            list: any[]
            wlListL: any[]
            wlListS: any[]
            wlList: any[]
        }>({
            showAdd: false,
            sideTitle: "新增调拨单",
            pageLoading: false,
            headerShow: true,
            rHeight: 0,
            list: [],
            wlListL: [],
            wlListS: [],
            wlList: []
        })

        const addHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库')
            } else {
                pageData.sideTitle = '新增调拨单'
                pageData.showAdd = true
            }
        }
        const selectHandler = () => {
            if (searchData.whTypeName == '' || searchData.wh == '' || searchData.firm == '') {
                Message.error('请先选择主页仓库类型或选择公司或仓库')
            } else {
                page.value = 1
                doRefresh()
            }
        }
        const sideOk = () => {
            if (pageData.list.length == 0) {
                Message.warning({
                    content: "请新增至少一条物料信息",
                    duration: 5000,
                });
                return
            }

            pageData.pageLoading = true;
            

            pageData.list.forEach(function (o: any) {
                if ((o['id'] + "").indexOf('add') != -1) {
                    o['id'] = null
                }
                o['firm']=searchData.firm2
                o['warehouseId']=searchData.wh2
            })
            formRef.value?.validate().then((err) => {
                if (!err) {
                    if (pageData.sideTitle === "新增五金领料单据") {
                        post({
                            url: "/wms/metalsRequisitionForm/add",
                            data: pageData.list,
                        }).then((res: any) => {
                            if (res.code === 200) {
                                pageData.showAdd = false;
                                formRef.value?.resetFields();
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                            doRefresh();
                        }).finally(() => {
                            doRefresh();
                            pageData.pageLoading = false
                        })
                    }
                }

            })
        }
        const whChange = (val: any) => {
            whList.value = []
            searchData.wh = ''
            searchData.firm = ''
        }
        watch(() => whService.whList.value, (o, n) => {


            whList.value = whService.whList.value
        })
        const companyChange = (val: any) => {
            whList.value = []
            searchData.wh = ''
            whService.getWarhouseList(searchData.firm, searchData.whTypeName)
        }

        let visible = ref(false)
        let whListMingxs = ref<any[]>([])
        const isXiang = async (val: any) => {
            const res: any = await whService.getWarhouseMinxList(val.orderNo, val.warehouseTypeName, val.warehouseName, val.firmId)
            if (res.code == 200) {
                whListMingxs.value = res.data
                visible.value = true
            }
        }

        const ckisPd = () => {
            if (searchData.whTypeName == '' || searchData.firm == '') {
                Message.error('请先选择仓库类型和所属工厂')
                return
            }
        }
        const isWhilist = (whName: any) => {
            let isWhId;
            whList.value.forEach((item: any) => {
                if (whName == item.warehouseName) {
                    isWhId = item.id
                }
            })
            whService.loadWHTypeFieldList({ warehouseId: isWhId, showType: 3 })
        }
        const companyChanges = (value: any) => {
            companyList.value.forEach((items: any) => {
                if (items.id == value) {
                    searchData.firmName2 = items.typeName ? items.typeName + '-' + items.firmName : items.firmName
                }
            })
            searchData.wh2 = ''
            whList2.value = []
            whService1.getWarhouseList(value, searchData.whTypeName)
        }
        watch(() => whService1.whList.value, (o, n) => {
            whList2.value = whService1.whList.value
        })
        const isWhNames = (val: any) => {
            whList2.value.forEach((item: any) => {
                if (val == item.id) {
                    searchData.wh2Name = item.warehouseName
                }
            })
        }
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
        }
        let tc: any[] = baseCol.map((o: any) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed'],
                width: 150
            }

            return obj
        })

        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const localeText1: any = ref(localeText)

        const tableColumnsWl = useTableColumn([
            {
                title: "物料大类",
                key: "materialL",
                dataIndex: "materialL",
                width: 150,
                slotName: 'materialL',
            },
            {
                title: "物料小类",
                key: "materialS",
                dataIndex: "materialS",
                width: 150,
                slotName: 'materialS',
            },
            {
                title: "物料编号",
                key: "materialCode",
                dataIndex: "materialCode",
                width: 150
            },

            {
                title: "物料名称",
                key: "materialName",
                dataIndex: "materialName",
                width: 150,
                slotName: 'materialName'
            },

            {
                title: "数量",
                key: "num",
                dataIndex: "num",
                width: 150,
                slotName: 'num'
            },
            {
                title: "单位",
                key: "unit",
                dataIndex: "unit",
                width: 150,

            }
        ]);
        let i = 0;
        //添加一行 点击新增按钮
        const addLine = () => {
            //在这个数组前面添加一行
            pageData.list.unshift({
                "id": "add" + (i++),
                "materialL": "",
                "materialS": "",
                "materialCode": "",
                "materialName": "",
                "num": "",
            })


        }

        // 删除
        const delLine = () => {
            if (selectedRowKeysWl.value.length === 0) {
                Message.error({
                    content: '请先勾选',
                    duration: 5000
                })
                return
            }
            pageData["list"] = pageData["list"].filter(function (o: any) {
                return selectedRowKeysWl.value.indexOf(o["id"]) === -1
            })

        }
        //下拉框得到焦点
        const focusSel = () => {
            getBigClass({ "bigClassName": "", deleteState: 0 });
        }
        //下拉数据
        const options = ref<any>(pageData.wlListL);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { bigClassName: value, deleteState: 0 }
                loading.value = true;
                getBigClass(ob);
                options.value = pageData.wlListL;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //查询物料大类
        function getBigClass(val: any) {
            post({
                url: "purchase/MaterialBigClass/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.wlListL = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //下拉数据
        const options1 = ref<any>(pageData.wlListS);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {

                const ob = {
                    bigClassName: value,
                }
                loading.value = true;
                selCxAll1(ob);
                options1.value = pageData.wlListS;
                loading1.value = false;
            } else {
                options1.value = []
            }
        };

        //下拉框查询 物料小类
        function selCxAll1(val: any) {
            post({
                url: "purchase/MaterialSubClass/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.wlListS = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ "bigClassName": "" });
        }
        //下拉数据
        const options2 = ref<any>(pageData.wlList);
        const handleSearch2 = (value: any) => {
            if (value) {
                const ob = { "subClassName": subClassName, "materialName": value }
                loading.value = true;
                getWlName(ob);
                options2.value = pageData.wlListS;
                loading.value = false;
            } else {
                options2.value = []
            }
        };

        //查询物料名称
        function getWlName(val: any) {
            post({
                url: "purchase/MaterialInfo/getFieldValueWms",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.wlList = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        let subClassName = ""
        //下拉框得到焦点
        const focusSel2 = (record: any) => {
            subClassName = record.materialS
            getWlName({ "subClassName": record.materialS, "materialName": "" });

        }
        //物料名称改变 拿到物料编号
        function changeWl(record: any, val: any) {
            let list2 = pageData.list.filter(function (o: any) {
                return (o['materialL'] == record['materialL'] && o['materialS'] == record['materialS'] && o['materialName'] == record['materialName'])
            })
            if (list2.length > 1) {
                record['materialName'] = ''
                record['materialCode'] = ''
                Message.warning({
                    content: '请不要重复选择物料！',
                    duration: 5000,
                })
                return
            }

            let list = pageData.wlList.filter(function (o: any) {
                return o['materialName'] == val
            })
            if (list.length > 0) {
                record['materialCode'] = list[0]['materialCode']
                record['unit'] = list[0]['unit']
            }
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            }

            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: 'wms/metalsRequisitionForm/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            pagination.page = 1
                            doRefresh()

                        } else {
                            Message.error({
                                content: '删除失败',
                                duration: 5000
                            })
                        }

                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        return {
            formRef,
            deleteHandler,
            changeWl,
            focusSel2,
            handleSearch2,
            options2,
            focusSel1,
            handleSearch1,
            loading1,
            options1,
            focusSel,
            options,
            loading,
            handleSearch,
            selectedRowKeysWl,
            sideOk,
            addLine,
            delLine,
            tableColumnsWl,
            localeText1,
            change1,
            PageSize,
            total,
            page,
            size,
            tc,
            defaultColDef,
            gridReady,
            gridOption,
            isWhNames,
            whList2,
            companyChanges,
            isWhilist,
            ckisPd,
            whListMingxs,
            isXiang,
            visible,
            companyChange,
            whChange,
            selectHandler,
            addHandler,
            companyList,
            whList,
            whTypeList,
            selectedRowKeys,
            whTypeFieldList,
            pagination,
            tableColumns,
            tableColumns1,
            table,
            rowKey,
            pageData,
            searchData,
            baseCol,
            whTypeFieldList1,
        };
    },
    components: { PageTabelLayout, QrcodeVue,  }
};
</script>
<style scoped lang="less">
.isTable {
    margin-top: 100px;
    width: 90%;
    margin: 0 auto;
    border: 1.2px solid #ccc;
    text-align: center;
    border-collapse: collapse;

    td {
        border: 1.2px solid #ccc;
    }

    th {
        border: 1.2px solid #ccc;
    }
}

#dy4 {
    width: 100%;

    #dys {
        width: 90%;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 20px;
    }
}

.cgisDatas {
    display: flex;
    justify-content: space-between;
}
</style>
